<template>
  <div class="order-container">
    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      :visible.sync="dialogVisible"
      width="50%">
      <div v-if="orderDetail" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ orderDetail.number }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ orderDetail.orderTime }}</el-descriptions-item>
          <el-descriptions-item label="用户名称">{{ orderDetail.userName }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ orderDetail.phone }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ orderDetail.amount }}</el-descriptions-item>
          <el-descriptions-item label="包装费">¥{{ orderDetail.packAmount }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">{{ getStatusText(orderDetail.status) }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ orderDetail.payMethod === 1 ? '微信支付' : '支付宝支付' }}</el-descriptions-item>
          <el-descriptions-item label="收货地址">{{ orderDetail.address }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ orderDetail.remark || '无' }}</el-descriptions-item>
        </el-descriptions>

        <div class="order-items" v-if="orderDetail.orderDetailList && orderDetail.orderDetailList.length > 0">
          <h3>订单明细</h3>
          <el-table :data="orderDetail.orderDetailList" border>
            <el-table-column prop="name" label="商品名称"></el-table-column>
            <el-table-column prop="number" label="数量" width="100"></el-table-column>
            <el-table-column prop="amount" label="金额" width="120">
              <template slot-scope="scope">
                ¥{{ scope.row.amount }}
              </template>
            </el-table-column>
            <el-table-column prop="dishFlavor" label="口味" width="150"></el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
    <!-- 订单统计 -->
    <el-row :gutter="20" class="statistics-container">
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="statistic-item">
            <div class="label">待接单</div>
            <div class="value">{{ orderStatistics.toBeConfirmed }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="statistic-item">
            <div class="label">已接单</div>
            <div class="value">{{ orderStatistics.confirmed }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="statistic-item">
            <div class="label">派送中</div>
            <div class="value">{{ orderStatistics.deliveryInProgress }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索过滤 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="form-inline">
        <el-form-item label="订单号">
          <el-input v-model="filterForm.number" placeholder="请输入订单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="filterForm.phone" placeholder="请输入手机号" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="filterForm.status" placeholder="请选择" clearable>
            <el-option label="待付款" value="1"></el-option>
            <el-option label="待接单" value="2"></el-option>
            <el-option label="已接单" value="3"></el-option>
            <el-option label="派送中" value="4"></el-option>
            <el-option label="已完成" value="5"></el-option>
            <el-option label="已取消" value="6"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 订单列表 -->
    <el-table
      :data="orderList"
      border
      style="width: 100%"
      v-loading="loading">
      <el-table-column
        prop="number"
        label="订单号"
        width="180">
      </el-table-column>
      <el-table-column
        prop="userName"
        label="用户名称"
        width="120">
      </el-table-column>
      <el-table-column
        prop="phone"
        label="手机号"
        width="120">
      </el-table-column>
      <el-table-column
        prop="amount"
        label="订单金额"
        width="120">
        <template slot-scope="scope">
          ¥{{ scope.row.amount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="订单状态"
        width="120">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="orderTime"
        label="下单时间"
        width="180">
      </el-table-column>
      <el-table-column
        label="操作"
        width="280">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleView(scope.row)">查看</el-button>
          <el-button
            size="mini"
            type="primary"
            v-if="scope.row.status === 2"
            @click="handleConfirm(scope.row)">接单</el-button>
          <el-button
            size="mini"
            type="danger"
            v-if="scope.row.status === 2"
            @click="handleReject(scope.row)">拒单</el-button>
          <el-button
            size="mini"
            type="warning"
            v-if="scope.row.status === 3"
            @click="handleDelivery(scope.row)">派送</el-button>
          <el-button
            size="mini"
            type="success"
            v-if="scope.row.status === 4"
            @click="handleComplete(scope.row)">完成</el-button>
          <el-button
            size="mini"
            type="danger"
            v-if="scope.row.status === 1 || scope.row.status === 2"
            @click="handleCancel(scope.row)">取消</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  searchOrders,
  cancelOrder,
  completeOrder,
  rejectOrder,
  confirmOrder,
  deliveryOrder,
  getOrderDetails,
  getOrderStatistics
} from '@/api/order'

export default {
  name: 'OrderManagement',
  data() {
    return {
      // 筛选表单
      filterForm: {
        number: '',
        status: '',
        phone: '',
        beginTime: '',
        endTime: '',
        dateRange: []
      },
      // 订单列表
      orderList: [],
      // 加载状态
      loading: false,
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 订单统计
      orderStatistics: {
        confirmed: 0,
        deliveryInProgress: 0,
        toBeConfirmed: 0
      },
      // 订单详情对话框
      dialogVisible: false,
      orderDetail: null
    }
  },
  created() {
    this.getOrderList()
    this.getOrderStatistics()
  },
  methods: {
    // 获取订单统计数据
    async getOrderStatistics() {
      try {
        const res = await getOrderStatistics()
        if (res.code === 1) {
          this.orderStatistics = res.data
        }
      } catch (error) {
        console.error('获取订单统计失败:', error)
      }
    },
    // 查询订单
    async getOrderList() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          number: this.filterForm.number,
          status: this.filterForm.status,
          phone: this.filterForm.phone
        }

        if(this.filterForm.number === '') {
          delete params.number
        }
        if(this.filterForm.status === '') {
          delete params.status
        }
        if(this.filterForm.phone === '') {
          delete params.phone
        }
        

        if (this.filterForm.dateRange && this.filterForm.dateRange.length === 2) {
          params.beginTime = this.filterForm.dateRange[0]
          params.endTime = this.filterForm.dateRange[1]
        }
        const res = await searchOrders(params)
        if (res.code === 1) {
          this.orderList = res.data.records
          this.total = res.data.total
        }
      } catch (error) {
        console.error('查询订单失败:', error)
        this.$message.error('查询订单失败')
      } finally {
        this.loading = false
      }
    },
    // 重置表单
    resetForm() {
      this.filterForm = {
        number: '',
        status: '',
        phone: '',
        beginTime: '',
        endTime: '',
        dateRange: []
      }
      this.currentPage = 1
      this.getOrderList()
    },
    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        1: 'warning',  // 待付款
        2: 'primary',  // 待接单
        3: 'info',     // 已接单
        4: '',         // 派送中
        5: 'success',  // 已完成
        6: 'danger',   // 已取消
        7: 'danger'    // 已退款
      }
      return statusMap[status] || ''
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '待付款',
        2: '待接单',
        3: '已接单',
        4: '派送中',
        5: '已完成',
        6: '已取消',
        7: '已退款'
      }
      return statusMap[status] || '未知状态'
    },
    // 查看订单
    async handleView(row) {
      try {
        const res = await getOrderDetails(row.id)
        if (res.code === 1) {
          this.orderDetail = res.data
          this.dialogVisible = true
        } else {
          this.$message.error('获取订单详情失败')
        }
      } catch (error) {
        console.error('获取订单详情失败:', error)
        this.$message.error('获取订单详情失败')
      }
    },
    // 完成订单
    async handleComplete(row) {
      try {
        await this.$confirm('确认将该订单标记为已完成?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await completeOrder(row.id)
        if (res.code === 1) {
          this.$message.success('订单已完成')
          this.getOrderList()
          this.getOrderStatistics()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('完成订单失败:', error)
          this.$message.error('完成订单失败')
        }
      }
    },
    // 取消订单
    async handleCancel(row) {
      try {
        const { value: cancelReason } = await this.$prompt('请输入取消原因', '取消订单', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (value) => {
            if (!value) {
              return '取消原因不能为空'
            }
            return true
          }
        })
        const res = await cancelOrder({ id: row.id, cancelReason })
        if (res.code === 1) {
          this.$message.success('订单已取消')
          this.getOrderList()
          this.getOrderStatistics()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消订单失败:', error)
          this.$message.error('取消订单失败')
        }
      }
    },
    // 接单
    async handleConfirm(row) {
      try {
        await this.$confirm('确认接受该订单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await confirmOrder({ id: row.id })
        if (res.code === 1) {
          this.$message.success('已接单')
          this.getOrderList()
          this.getOrderStatistics()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('接单失败:', error)
          this.$message.error('接单失败')
        }
      }
    },
    // 拒单
    async handleReject(row) {
      try {
        const { value: rejectionReason } = await this.$prompt('请输入拒单原因', '拒绝订单', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (value) => {
            if (!value) {
              return '拒单原因不能为空'
            }
            return true
          }
        })
        const res = await rejectOrder({ id: row.id, rejectionReason })
        if (res.code === 1) {
          this.$message.success('已拒单')
          this.getOrderList()
          this.getOrderStatistics()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('拒单失败:', error)
          this.$message.error('拒单失败')
        }
      }
    },
    // 派送订单
    async handleDelivery(row) {
      try {
        await this.$confirm('确认派送该订单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await deliveryOrder(row.id)
        if (res.code === 1) {
          this.$message.success('订单已派送')
          this.getOrderList()
          this.getOrderStatistics()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('派送订单失败:', error)
          this.$message.error('派送订单失败')
        }
      }
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getOrderList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.getOrderList()
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getOrderList()
    }
  }
}
</script>

<style scoped>
.order-container {
  padding: 20px;
}

.statistics-container {
  margin-bottom: 20px;
}

.statistic-item {
  text-align: center;
  padding: 20px 0;
}

.statistic-item .label {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.statistic-item .value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.filter-container {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.order-detail {
  padding: 20px;
}

.order-items {
  margin-top: 30px;
}

.order-items h3 {
  margin-bottom: 20px;
  font-weight: normal;
  color: #303133;
}
</style>